import { SettingOutlined } from '@ant-design/icons';
import { Button, Checkbox, Popover } from 'antd';
import CheckboxGroup from 'antd/lib/checkbox/Group';
import React, { useState } from 'react';

/**
 * options: 选项 columns: 表格列 setTableColumns: 改变table列
 */
export default function ColumnsFilter({ options, columns, setTableColumns, type = 'button' }: any) {
  const [checkedAll, setCheckedAll] = useState({
    indeterminate: false,
    checkAll: true,
  });
  const [checked, setChecked] = useState(options);
  // 筛选列
  const handleFilterColumns = (checkedList: any[]) => {
    setChecked(checkedList);
    setCheckedAll((pre) => ({
      checkAll: checkedList.length === 0 ? false : pre.checkAll,
      indeterminate: !!checkedList.length && checkedList.length < options.length,
    }));
    const res = columns.filter((item: any) => !!checkedList.includes(item.title));
    setTableColumns(res);
  };
  // 全选
  const onCheckAllChange = (e: any) => {
    setCheckedAll({
      indeterminate: false,
      checkAll: e.target.checked,
    });
    handleFilterColumns(e.target.checked ? options : []);
  };
  const titles = (
    <Checkbox
      indeterminate={checkedAll.indeterminate}
      onChange={onCheckAllChange}
      checked={checkedAll.checkAll}
    >
      全选
    </Checkbox>
  );
  const content = (
    <CheckboxGroup
      options={options}
      style={{ width: '200px' }}
      onChange={handleFilterColumns}
      value={checked}
    />
  );
  return (
    <div style={{ marginBottom: 5, marginTop: 10, display: 'inline-block' }}>
      <Popover
        placement="bottomLeft"
        style={{ width: '400px' }}
        title={titles}
        content={content}
        trigger="click"
      >
        {type === 'icon' ? (
          <SettingOutlined style={{ fontSize: '20px' }} />
        ) : (
          <Button type="primary">筛选列</Button>
        )}
      </Popover>
    </div>
  );
}
